package com.chen.util;

import cn.hutool.core.io.FileUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author:chenao
 * @DATE:2022/3/3 19:51
 */
@Component
public class FileUtils {

    @Autowired
    private UrlUtil urlUtil;

    /**
     * 保存文件到服务器upload
     * @param file 前端上传的文件
     * @param path 静态文件目录，格式为:"swiper"
     * @return 文件绝对路径和Url
     */
    public Map<String,String> saveFile(MultipartFile file,String path){
        Map<String,String> map = new HashMap<>();
        FileOutputStream out = null;
        try {
            String fileName = UUID.randomUUID() +".jpg";
            //先判断父文件夹是否存在
            if(!FileUtil.exist(PathUtils.getUploadPath() + path)){
                FileUtil.mkdir(PathUtils.getUploadPath() + path);
            }
            //格式为:xxx/upload/swiper/filename
            String filePath = PathUtils.getUploadPath() + path +File.separator + fileName;
            out = new FileOutputStream(filePath);
            out.write(file.getBytes());
            out.flush();
            out.close();
            map.put("filePath",filePath);
            map.put("imageUrl",urlUtil.createImageUrl(path,fileName));
            return map;
        } catch (Exception e) {
            System.out.println("保存文件失败"+file.getName());
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
